package com.clinbrain;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Xiahu
 * @create 2022/6/21 0021
 */
public class HttpTool {


    public static String doPost(String url, Map<String, Object> paramMap) {
        int retry = 3;

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig
                .custom()
                .setConnectTimeout(999999999)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(999999999)// 设置连接请求超时时间
                .setSocketTimeout(999999999)// 设置读取数据连接超时时间
                .build();
        httpPost.setConfig(requestConfig);
        // httpPost.addHeader("Content-Type", "application/json");
        List<NameValuePair> nvps = new ArrayList<>();
        paramMap.entrySet().forEach(entry -> {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        });

        while (retry > 0) {
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
                response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    return EntityUtils.toString(entity, "UTF-8");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                retry--;
            }
        }
        throw new RuntimeException("connect interface timeout");
    }
}
